﻿#include "scannerhelper.h"
#include <qdebug.h>

ScannerHelper *ScannerHelper::instance()
{
    static ScannerHelper global;
    return &global;
}

ScannerHelper::ScannerHelper(QObject *parent)
    : QObject{parent}
{

}

QString ScannerHelper::initScanner()
{
    QStringList m_serialPortName;
     QStringList m_serialPortName2;
    foreach(const QSerialPortInfo & info, QSerialPortInfo::availablePorts())
    {
        qDebug() << "serialPortName:" << info.portName()<<info.serialNumber()<<info.description();
        m_serialPortName2 << info.portName();
        if(!info.description().isEmpty() && info.serialNumber().toLower() == "1234567890abcd")
        {
            m_serialPortName << info.portName();
        }
    }
    if(m_serialPortName.size() == 0 && m_serialPortName2.size() > 0)
    {
        m_serialPortName.append(m_serialPortName2[0]);
    }
    if(m_serialPortName.size() == 0)
    {
        return tr(u8"未发现扫码枪，请链接扫码枪后重新启动本程序");
    }
    qDebug() << "current serialPortName:" << m_serialPortName[0];
    m_serialPort = new QSerialPort(this);//实例化串口类一个对象

    if (m_serialPort->isOpen())//如果串口已经打开了 先给他关闭了
    {
        m_serialPort->clear();
        m_serialPort->close();
    }

    //设置串口名字 假设我们上面已经成功获取到了 并且使用第一个
    m_serialPort->setPortName(m_serialPortName[0]);
    if (!m_serialPort->open(QIODevice::ReadWrite))//用ReadWrite 的模式尝试打开串口
    {
        return tr(u8"扫码枪打开失败，请链接扫码枪后重新启动本程序");
    }
    //打开成功

    m_serialPort->setBaudRate(QSerialPort::Baud115200, QSerialPort::AllDirections);//设置波特率和读写方向
    m_serialPort->setDataBits(QSerialPort::Data8);		//数据位为8位
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
    m_serialPort->setParity(QSerialPort::NoParity);	//无校验位
    m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位

    //连接信号槽 当下位机发送数据QSerialPortInfo 会发送个 readyRead 信号,我们定义个槽void receiveInfo()解析数据
    connect(m_serialPort, SIGNAL(readyRead()), this, SLOT(receiveInfo()));
    return tr(u8"扫码枪连接成功");
}

void ScannerHelper::receiveInfo()
{
    QByteArray info = m_serialPort->readAll();
    QString data=QString(info);
    data=data.replace("\r","");
    data=data.replace("\n","");
    qDebug()<<"====recv scanner data:"<<data;
    emit recvScannerData(data);
}
